﻿const {
  readdirSync,
  existsSync,
  fstat,
  writeFileSync,
  writeFile,
} = require('fs');
const { yParser } = require('@umijs/utils');
const { join } = require('path');
const prettier = require('prettier');
const exec = require('./utils/exec');
const { exec: execShell } = require('child_process');

const args = yParser(process.argv);

// utils must build before core
// runtime must build before renderer-react

const execCommand = (buildCommand) => {
  return new Promise((resolve, reject) => {
    execShell(buildCommand, async (error, stdout, stderr) => {
      if (error) {
        reject({
          error,
          success: false,
        });
      } else if (stderr) {
        reject({
          error: stderr,
          success: false,
        });
      } else {
        resolve({
          stdout,
          success: true,
        });
      }
    });
  });
};

(async () => {
  let packagesPath = join(__dirname, '../packages');
  const pkgList = readdirSync(packagesPath)
    .filter((pkg) => pkg.charAt(0) !== '.')
    .map((pkg) => {
      const package_path = join(packagesPath, pkg);
      if (!existsSync(join(package_path, 'package.json'))) return;
      const json = require(join(package_path, 'package.json'));
      return {
        name: json.name,
        version: json.version,
      };
    });

  const file_content = `

  export const version = {
      ${pkgList
        .map((pak) => {
          return `"${pak.name}": '${pak.version}'`;
        })
        .join(',\n    ')}
  }
  `;

  writeFileSync(
    join(packagesPath, 'components', '/src/version.ts'),
    prettier.format(file_content, { parser: 'typescript' }).toString(),
  );

  const package_path = join(packagesPath, 'components');
  if (!existsSync(join(package_path, 'package.json'))) return;
  const defaultConfigs = require(join(package_path, 'package.json'));
  let flag = false;
  pkgList.forEach((e) => {
    const packVersion = defaultConfigs.dependencies[e.name];
    if (packVersion && packVersion !== e.version) {
      flag = true;
      defaultConfigs.dependencies[e.name] = e.version;
    }
  });
  if (!flag) return;
  writeFileSync(
    join(packagesPath, 'components', '/package.json'),
    prettier
      .format(JSON.stringify(defaultConfigs), { parser: 'json' })
      .toString(),
  );
  if (args?.noCommit) return;
  const status = await execCommand('git status -s');
  if (status && status.success && status.stdout) {
    await exec('git', ['add', './packages/components/package.json']);
    await exec('git', ['commit', '-m "fix: components依赖修改"']);
    await exec('git', ['push', 'origin', 'master']);
  }
})();
